package store.lunangangster.engine.impl.repository;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import store.lunangangster.engine.bpmn.parser.BpmnParser;
import store.lunangangster.engine.bpmn.parser.BpmnParsers;
import store.lunangangster.engine.impl.entity.DeploymentEntity;
import store.lunangangster.engine.impl.entity.ProcessDefinitionEntity;
import store.lunangangster.engine.impl.entity.ResourceEntity;

public class DeploymentParseBuilder {

  protected DeploymentEntity deployment;
  protected BpmnParsers bpmnParsers;

  protected DeploymentParseBuilder(DeploymentEntity deployment, BpmnParsers bpmnParsers) {
    this.deployment = deployment;
    this.bpmnParsers = bpmnParsers;
  }

  /**
   * 根据所构造的DeploymentEntity对象来构建DeploymentParse对象。主要包括对Resource的解析，构造Bpmn对象
   * @return
   */
  public DeploymentParse build() {
    List<ProcessDefinitionEntity> processDefinitionEntities = new ArrayList<>();
    Map<ProcessDefinitionEntity, ResourceEntity> processDefinitionToResourceMap = new LinkedHashMap<>();
    Map<ProcessDefinitionEntity, BpmnParser> processDefinitionToBpmnParserMap = new LinkedHashMap<>();
    for (ResourceEntity resourceEntity : deployment.getResources()) {
      BpmnParser bpmnParser = bpmnParsers.createParser().setResource(resourceEntity).build();
      // parse Bpmn
      bpmnParser.parse();
      processDefinitionEntities.addAll(bpmnParser.getProcessDefinitionEntities());
      for (ProcessDefinitionEntity processDefinitionEntity : bpmnParser.getProcessDefinitionEntities()) {
        processDefinitionToResourceMap.put(processDefinitionEntity, resourceEntity);
        processDefinitionToBpmnParserMap.put(processDefinitionEntity, bpmnParser);
      }
    }
    return new DeploymentParse(deployment,
        processDefinitionEntities,
        processDefinitionToResourceMap,
        processDefinitionToBpmnParserMap);
  }
}
